<template>
  <div class="orders-page">
    <h1 class="page-title">我的订单</h1>
    
    <div class="order-filters">
      <el-select v-model="filterStatus" placeholder="筛选订单状态">
        <el-option label="全部" value="" />
        <el-option label="待接单" value="pending" />
        <el-option label="处理中" value="processing" />
        <el-option label="已完成" value="completed" />
        <el-option label="已取消" value="cancelled" />
      </el-select>
    </div>
    
    <div v-if="orders.length > 0" class="order-list">
      <div class="order-item" v-for="order in filteredOrders" :key="order.orderId">
        <div class="order-header">
          <span class="order-id">订单号：{{ order.orderId }}</span>
          <span class="order-date">{{ formatDate(order.createdAt) }}</span>
          <el-tag :type="getStatusTagType(order.status)">{{ getStatusText(order.status) }}</el-tag>
        </div>
        
        <div class="order-products">
          <div class="product-item" v-for="product in order.products" :key="product.productId">
            <img :src="product.image_url" alt="Product" class="product-image" />
            <div class="product-info">
              <h3>{{ product.name }}</h3>
              <p>单价：¥{{ product.price.toFixed(2) }}</p>
              <p>数量：{{ product.quantity }}</p>
            </div>
          </div>
        </div>
        
        <div class="order-footer">
          <div class="order-total">
            <span>总计：</span>
            <span class="total-price">¥{{ order.totalPrice.toFixed(2) }}</span>
          </div>
          <div class="order-actions">
            <el-button v-if="order.status === 'pending'" type="primary" @click="payOrder(order.orderId)">
              支付订单
            </el-button>
            <el-button v-if="order.status === 'pending'" @click="cancelOrder(order.orderId)">
              取消订单
            </el-button>
            <el-button v-if="order.status === 'processing'" @click="checkLogistics(order.orderId)">
              查看物流
            </el-button>
            <el-button v-if="order.status === 'completed'" @click="leaveReview(order.orderId)">
              评价商品
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else class="empty-orders">
      <img src="https://picsum.photos/200/150?random=10" alt="No Orders" />
      <p>您还没有任何订单</p>
      <el-button @click="$router.push('/main/home')">去购物</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();
const currentUser = ref(JSON.parse(localStorage.getItem('currentUser') || '{}'));
const orders = ref([]);
const filterStatus = ref('');

onMounted(() => {
  if (!currentUser.value.userId) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }

  const ordersKey = `user_${currentUser.value.userId}_orders`;
  const storedOrders = localStorage.getItem(ordersKey);
  
  if (storedOrders) {
    orders.value = JSON.parse(storedOrders);
    console.log('订单数据:', orders.value);
  }
});

const filteredOrders = computed(() => {
  if (!filterStatus.value) return orders.value;
  return orders.value.filter(order => order.status === filterStatus.value);
});

const formatDate = (dateString) => new Date(dateString).toLocaleString();

const getStatusText = (status) => ({
  pending: '待接单',
  processing: '处理中',
  completed: '已完成',
  cancelled: '已取消',
}[status] || '未知状态');

const getStatusTagType = (status) => ({
  pending: 'warning',
  processing: 'primary',
  completed: 'success',
  cancelled: 'danger',
}[status] || 'info');

// 支付订单
const payOrder = (orderId) => {
  const orderIndex = orders.value.findIndex(order => order.orderId === orderId);
  if (orderIndex > -1) {
    orders.value[orderIndex].status = 'processing';
    const ordersKey = `user_${currentUser.value.userId}_orders`;
    localStorage.setItem(ordersKey, JSON.stringify(orders.value));
    ElMessage.success('支付成功');
  }
};

// 取消订单
const cancelOrder = (orderId) => {
  const orderIndex = orders.value.findIndex(order => order.orderId === orderId);
  if (orderIndex > -1) {
    orders.value[orderIndex].status = 'cancelled';
    const ordersKey = `user_${currentUser.value.userId}_orders`;
    localStorage.setItem(ordersKey, JSON.stringify(orders.value));
    ElMessage.success('订单已取消');
  }
};

</script>


<style scoped>
/* 保持原有样式不变 */
.orders-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.order-filters {
  margin-bottom: 20px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-item {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #eee;
}

.order-id {
  font-weight: 500;
}

.order-date {
  color: #666;
  font-size: 14px;
}

.order-products {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.product-item {
  display: flex;
  gap: 10px;
  align-items: center;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 4px;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
}

.product-info h3 {
  font-size: 14px;
  margin-bottom: 5px;
}

.product-info p {
  font-size: 13px;
  color: #666;
  margin: 0;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-top: 1px solid #eee;
}

.order-total {
  font-weight: 500;
}

.total-price {
  color: #E05649;
  font-size: 16px;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.empty-orders {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  text-align: center;
}

.empty-orders img {
  width: 200px;
  height: 150px;
  object-fit: contain;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-orders p {
  margin-bottom: 15px;
  color: #666;
}
</style>